package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /*
     * 文件上传
     *
     * */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件夹，需要转存到别的位置，不然的话这次请求完成就会被删除
        log.info(file.toString());
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUid重新生成文件名，防止重名
        String filename = UUID.randomUUID().toString() + substring;
        //创建一个目录对象
        File file1 = new File(basePath);
        //判断当前目录是否存在
        if (!file1.exists()) {
            //目录不存在，需要创建
            file1.mkdirs();
        }


        try {
            file.transferTo(new File(basePath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }

    @GetMapping("/download")
    public R download(HttpServletResponse response, String name) {

        log.info("文件下载，文件名为{}", name);
        try {
            //获取访问路径
            String filename = basePath + name;
            //获取文件的字节数组

            byte[] bytes = FileCopyUtils.copyToByteArray(new File(filename));
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success();
    }
}
